package cn.sumpu.app.coolsk.biz.impl;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import magick.MagickException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.sumpu.app.coolsk.bean.ImageWeb;
import cn.sumpu.app.coolsk.biz.ImageBiz;
import cn.sumpu.app.coolsk.constant.Constant;
import cn.sumpu.app.coolsk.exception.AppBusinessException;
import cn.sumpu.toolkit.common.http.HttpProxy;
import cn.sumpu.toolkit.common.util.Common;


public class ImageBizImpl implements ImageBiz {

	private final static Logger logger = LoggerFactory
			.getLogger(ImageBizImpl.class);
	
	static {
		System.setProperty("jmagick.systemclassloader","no");
	}

	private String uploadPath;
	private String imageServer;
	private String imageDir;
	
	public void setUploadPath(String uploadPath) {
		this.uploadPath = uploadPath;
	}

	public void setImageServer(String imageServer) {
		this.imageServer = imageServer;
	}

	public void setImageDir(String imageDir) {
		this.imageDir = imageDir;
	}

	@Override
	public boolean checkUploadSize(HttpServletRequest request)
			throws AppBusinessException {
		try {
			MultipartHttpServletRequest re = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> map = re.getFileMap();
			List<MultipartFile> fileList = new ArrayList<MultipartFile>();
			for (Object obj : map.values()) {
				MultipartFile file = (MultipartFile) obj;
				fileList.add(file);
			}
			if (fileList.size() > 0) {
				MultipartFile fj = fileList.get(0);
				if (fj.getSize() > Constant.PHOTO_SIZE_ALLOW) {
					return false;
				} else
					return true;
			}
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			throw new AppBusinessException("check upplad size failure!", e);
		}

	}


	@Override
	public ImageWeb uploadOneImg(HttpServletRequest request,String picType)
			throws AppBusinessException {
		ImageWeb imageWeb = new ImageWeb();
		imageWeb.setState("上传失败！");
		try {
			MultipartHttpServletRequest re = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> map = re.getFileMap();
			List<MultipartFile> fileList = new ArrayList<MultipartFile>();
			for (Object obj : map.values()) {
				MultipartFile file = (MultipartFile) obj;
				fileList.add(file);
			}
			if (fileList.size() > 0) {
				
				MultipartFile fj = fileList.get(0);
				String fn = fj.getOriginalFilename();
				if (null != fn && fn.length() > 0) {
					// 图片不能超过允许的大小
					if (fj.getSize() > Constant.PHOTO_SIZE_ALLOW) {
						imageWeb.setSizeAllow(false);
						return imageWeb;
					} else {
						
						InputStream buffin = new ByteArrayInputStream(fj.getBytes());
						BufferedImage bi = ImageIO.read(buffin);
						if (bi != null) {
							String now = Common.getFormatDate(new Date(), "yyyyMMdd");
							String uuid = UUID.randomUUID().toString();
							String imageFix = fn.substring(fn.lastIndexOf("."));

							String serverUrl = imageServer + "receiveImage.htm";
							String savePath = uploadPath + "/" + picType + "/" + now;
							requestSaveImage(serverUrl, savePath, uuid + imageFix, fj.getBytes());
							imageWeb.setImageServer(imageServer);
							imageWeb.setImageUrl(uploadPath + "/" + picType + "/" + now + "/" + uuid + imageFix);
							imageWeb.setWidth(bi.getWidth());
							imageWeb.setHeight(bi.getHeight());
							imageWeb.setSizeAllow(true);
							imageWeb.setState("SUCCESS");
						}

						return imageWeb;

					}

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return imageWeb;
		}
		return imageWeb;
	}

	@Override
	public void requestSaveImage(String serverUrl, String savePath,
			String saveFilename, byte[] imageData) throws AppBusinessException {
		try { 
			String ret = HttpProxy.sendImage(serverUrl, savePath, saveFilename,
					imageData);
			if (null == ret || "error".equals(ret)) {
				if (logger.isErrorEnabled()) {
					logger.error("Request save image failure!");
				}
				throw new AppBusinessException();
			}
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("Request save image failure!", e);
			}
			throw new AppBusinessException(e);
		}
	}

	@Override
	public void requestDeleteImage(String serverUrl, String imageFile)
			throws AppBusinessException {
		try {
			String ret = HttpProxy.deleteImage(serverUrl, imageFile);
			if (null == ret || "error".equals(ret)) {
				if (logger.isErrorEnabled()) {
					logger.error("Request delete image failure!");
				}
				throw new AppBusinessException();
			}
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("Request delete image failure!", e);
			}
			throw new AppBusinessException(e);
		}
	}

	@Override
	public void requestDeleteImage(String imageFile)
			throws AppBusinessException {
		requestDeleteImage(imageServer +"deleteImage.htm", imageFile);
	}

	@Override
	public void saveImage(byte[] in, String savePath, String saveFilename)
			throws AppBusinessException {
		try {
			String path = imageDir + File.separator + savePath + File.separator;
			File filePath = new File(path);   
			if (!filePath.exists()) {
				filePath.mkdirs();
			}
			String fileName = path + saveFilename;
			File f = new File(fileName);
			FileOutputStream out = new FileOutputStream(f);
	        out.write(in);
	        out.close();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("Save image failure!", e);
			}
			throw new AppBusinessException(e);
		}
	}

	@Override
	public void deleteImage(String imageFile) throws AppBusinessException {
		try {
			String fileName = imageDir + File.separator + imageFile;
			File file = new File(fileName);
			file.delete();
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("Delete image failure!", e);
			}
			throw new AppBusinessException(e);
		}
	}

	
	public static void main(String[] args) throws MagickException {
		
	}



}
